package com.zh.media.https;

import android.util.Log;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @Description:     mqtt管理
 * @Author:         mark
 * @CreateDate:     2024/11/6 10:29
 * @UpdateUser:     更新者：
 * @UpdateDate:     2024/11/6 10:29
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
public class MqttManager {

    //private static final String MQTT_BROKER_URL = "tcp://esl.vigiot.com:1885";
    private static final String MQTT_BROKER_URL = "tcp://124.71.63.168:1885";
    private static final String CLIENT_ID = "AndroidClient123456";
    private String userName = "aa";                    //然后是你的用户名
    private String passWord = "123456";                    //用户名对应的密码，

    private MqttClient mqttClient;
    public MqttConnectOptions options;//配置  保存控制客户端连接到服务器的方式的选项集
    public void connectMqtt() {
        try {
            // Construct the MQTT client
            //mqttClient = new MqttClient(MQTT_BROKER_URL, CLIENT_ID);
            //实例化mqtt_client，填入我们定义的serverUri和clientId，然后MemoryPersistence设置clientid的保存形式，默认为以内存保存
            mqttClient = new MqttClient(MQTT_BROKER_URL,CLIENT_ID,new MemoryPersistence());
            //创建并实例化一个MQTT的连接参数对象
            options = new MqttConnectOptions();
            //然后设置对应的参数
            //options.setUserName(userName);                  //设置连接的用户名
            //options.setPassword(passWord.toCharArray());    //设置连接的密码
            options.setConnectionTimeout(60);               // 设置超时时间，单位为秒
            options.setKeepAliveInterval(60);               //设置心跳,30s
            options.setAutomaticReconnect(true);            //是否重连
            //设置是否清空session,设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);


            // Set the callback function for incoming messages
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // Called when a message arrives
                    Log.e("mqtt", "mqtt收到消息"+message.toString());
                    if (message != null)
                    System.out.println("mqtt"+message.toString());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // Called when a message is published
                }

                @Override
                public void connectionLost(Throwable cause) {
                    // Called when the connection to the server is lost
                    //连接丢失后，一般在这里面进行重连
                    try {
                        mqttClient.reconnect();
                    } catch (MqttException e) {
                        // 处理异常，例如打印堆栈跟踪或执行其他恢复操作
                        e.printStackTrace();
                    }
                }
            });

            mqttClient.connect(options);

            // 连接成功的判断
            if(mqttClient.isConnected()) {
                Log.e("mqtt", "mqtt连接成功");
                // 连接成功后的操作

            }


            // Subscribe to a topic, if needed
            mqttClient.subscribe("media/#");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     /**
      * @description 断开连接
      * @date: 2024/11/6 10:30
      * @author: mark
      * @param
      * @return
      */
    public void disconnectMqtt() {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     /**
      * @description push订阅消息
      * @date: 2024/11/6 10:31
      * @author: mark
      * @param
      * @return
      */
    public void publishMessage(String topic, String message) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                MqttMessage mqttMessage = new MqttMessage(message.getBytes());
                mqttClient.publish(topic, mqttMessage);
            }else {
                mqttClient.connect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void subscribe(String topic, MqttCallback mqttCallback){
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.setCallback(mqttCallback);
                mqttClient.subscribe(topic);
            }else {
                mqttClient.connect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
